package com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.SingleCarSQL;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;
import com.rey.material.widget.Button;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//AppCompatActivity
public class ConvenientPaymentActivity extends BaseActivity implements View.OnClickListener {

    private Handler handler;
    private LinearLayout orderAndMoneyInfo;
    private LinearLayout carOrderDetail;
    private TextView totalMoneyTextView;
    private TextView nullData;
    private TextView remainOrderTextview;
    private LinearLayout cardBackground2;
    private LinearLayout cardBackground3;
    private Button paymentButton;
    private Button getSingleCarButton;
    private Button batchPaymentButton;
    private EditText editText;
    private String unPaySingleCarTotal = "0";
    private String unPaySingleCarTotalPrice;
    private SingleCarSQL singleCarSQL;


    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_convenient_payment_layout);

        init();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init(){
        handler = new Handler();
        orderAndMoneyInfo = findViewById(R.id.id_order_and_money_info);
        carOrderDetail = findViewById(R.id.id_car_order_detail);
        totalMoneyTextView = findViewById(R.id.id_total_money);
        nullData = findViewById(R.id.id_null_data);
        remainOrderTextview = findViewById(R.id.id_remain_order);
        cardBackground2 = findViewById(R.id.id_car_order_information2);
        cardBackground3 = findViewById(R.id.id_car_order_information3);

        getSingleCarButton = findViewById(R.id.id_get_single_car);
        getSingleCarButton.setOnClickListener(this);

        paymentButton = findViewById(R.id.id_batch_payment);
        paymentButton.setOnClickListener(this);

        batchPaymentButton = findViewById(R.id.id_batch_payment);
        batchPaymentButton.setOnClickListener(this);

        editText = findViewById(R.id.id_license_plate);
        editText.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View view, MotionEvent event){
                cardBackground2.setVisibility(View.GONE);
                cardBackground3.setVisibility(View.GONE);
                return true;
            }
        });

        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        String carNumber = pref.getString("carNumber", "");
        if (!"".equals(carNumber)){
            editText.setText(carNumber);
            editText.setSelection(editText.getText().length());
            showCarOrderList(carNumber);
        }else{
            new Thread(){
                public void run(){
                    handler.post(runnableHiddenInfo);
                }
            }.start();
        }
    }

    @Override
    public void onClick(View v){
        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
        switch(v.getId()){
            case R.id.id_get_single_car:
                String carNumber = editText.getText().toString().trim();
                if ("".equals(carNumber)){
                    Toast.makeText(getApplicationContext(), Constant.ON_LICENSEPLATE, Toast.LENGTH_LONG).show();
                }else{
                    carNumber = carNumber.toUpperCase();
                    editor.putString("carNumber", carNumber);
                    editor.apply();
                    showCarOrderList(carNumber);
                }
                cardBackground2.setVisibility(View.VISIBLE);
                cardBackground3.setVisibility(View.VISIBLE);
                break;
            case R.id.id_to_payment:
            case R.id.id_car_order_information:
                if (orderAndMoneyInfo.getVisibility() == View.VISIBLE){
                    Intent intent = new Intent(ConvenientPaymentActivity.this, CarOrderActivity.class);
                    intent.putExtra("singleCarID", singleCarSQL.getSingleCarId().toString());
                    intent.putExtra("flag", "false");
                    startActivity(intent);
                }
                break;
            case R.id.id_batch_payment:
                Intent intent = new Intent(ConvenientPaymentActivity.this, BatchPaymentActivity.class);
                intent.putExtra("carNumber", editText.getText().toString().toUpperCase());
                startActivity(intent);
                break;
        }
    }

    private void showCarOrderList(String carNumber){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_SINGLE_CAR + "?plate=" + carNumber + "&searchType=" + 0 + "&searchCount=" + 1 + "&pageSize=" + 1000 + "&page=" + 1)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject jsonObject = joOut.getJSONObject("object");
                    if (jsonObject == null){
                        new Thread(){
                            public void run(){
                                handler.post(runnableHiddenInfo);
                            }
                        }.start();
                    }else{
                        JSONObject joIn = jsonObject.getJSONArray("records").getJSONObject(0);
                        unPaySingleCarTotal = joIn.getString("unPaySingleCarTotal");
                        unPaySingleCarTotalPrice = joIn.getString("unPaySingleCarTotalPrice");
                        String streetName = joIn.getString("streetName");
                        String streetInfo = streetName.charAt(0) + "***";
                        Date singleCarEndTime = joIn.getDate("parkEndTime");
                        Date singleCarStartTime = joIn.getDate("parkStartTime");
                        Double singleCarPrice = joIn.getDouble("price");
                        Double singleCarPaid = joIn.getDouble("paidPrice");
                        Long singleCarId = joIn.getLong("singleCarId");
                        singleCarSQL = new SingleCarSQL();
                        singleCarSQL.setRouteLocationName(streetName);
                        singleCarSQL.setSingleCarStartTime(singleCarStartTime);
                        singleCarSQL.setSingleCarEndTime(singleCarEndTime);
                        singleCarSQL.setSingleCarPrice(singleCarPrice);
                        singleCarSQL.setSingleCarPaid(singleCarPaid);
                        singleCarSQL.setSingleCarId(singleCarId);
                        new Thread(){
                            public void run(){
                                handler.post(runnableShowInfo);
                            }
                        }.start();
                    }
                }
            }
        });
    }

    Runnable runnableHiddenInfo = new Runnable(){
        @Override
        public void run(){
            orderAndMoneyInfo.setVisibility(View.GONE);
            carOrderDetail.setVisibility(View.GONE);
            nullData.setVisibility(View.VISIBLE);
            paymentButton.setVisibility(View.GONE);
            batchPaymentButton.setVisibility(View.GONE);
        }
    };
    Runnable runnableShowInfo = new Runnable() {
        @Override
        public void run() {
            orderAndMoneyInfo.setVisibility(View.VISIBLE);
            carOrderDetail.setVisibility(View.GONE);
            nullData.setVisibility(View.GONE);
            paymentButton.setVisibility(View.VISIBLE);
            if (Integer.valueOf(unPaySingleCarTotal ) > 1){
                batchPaymentButton.setVisibility(View.VISIBLE);
            }

            TextView streetName = findViewById(R.id.id_street_name);
            TextView startTime = findViewById(R.id.id_start_time);
            TextView endTime = findViewById(R.id.id_end_time);
            TextView payMoney = findViewById(R.id.id_pay_money);
            LinearLayout linearLayout = findViewById(R.id.id_car_order_information);
            linearLayout.setOnClickListener(ConvenientPaymentActivity.this);
            remainOrderTextview.setText(unPaySingleCarTotal + "tiao");
            totalMoneyTextView.setText(unPaySingleCarTotalPrice + "yuan");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            streetName.setText(singleCarSQL.getRouteLocationName());
            String singleCarStartTime = simpleDateFormat.format(singleCarSQL.getSingleCarStartTime());
            String singleCarEndTime = simpleDateFormat.format(singleCarSQL.getSingleCarEndTime());
            startTime.setText(singleCarStartTime);
            endTime.setText(singleCarEndTime);
            double singleCarPrice = singleCarSQL.getSingleCarPrice();
            double singleCarPaid = singleCarSQL.getSingleCarPaid();
            String price;
            if (singleCarPaid > 0 && singleCarPaid < singleCarPrice){
                price = new BigDecimal(singleCarPrice - singleCarPaid).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            }else{
                price = new BigDecimal(singleCarPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            }
            payMoney.setText(price);
        }
    };

    @Override
    protected void onRestart(){
        super.onRestart();
        String carNumber = editText.getText().toString().toUpperCase();
        showCarOrderList(carNumber);
    }
}
